package com.umf.b2b.demo.file;

import com.umf.b2b.model.file.MaterialsFileUpload;
import com.umpay.http.UMFFileClient;
import com.umpay.mer.ConfigContext;
import org.springframework.util.DigestUtils;

import java.io.*;
import java.util.Map;

/**
* @author zhanglz:
* @ClassName UploadFile.java
* @Description 
*/

public class UploadFile {
    static ConfigContext apiContext;
    static String url = "http://b2b.umfintech.com/merAccess/file/upload/materials";
    static {
        apiContext = new ConfigContext(url, "90000002");
    }

    public static void main(String[] args) throws Exception {
        String materialsFile = "C:\\Users\\lifeng\\Desktop\\demo_04.rar";
        uploadFile(materialsFile);
    }

    static void uploadFile(String materialsFile) throws Exception {
        MaterialsFileUpload materialsFileUpload = new MaterialsFileUpload();
        materialsFileUpload.setMer_id("90000002");
        materialsFileUpload.setUser_type("3");
        materialsFileUpload.setUser_id("00042493");
        File file = new File(materialsFile);
        materialsFileUpload.setMd5_cipher(DigestUtils.md5DigestAsHex(getBytes(file)));
        materialsFileUpload.setNotify_url("http://www.baidu.com");
        try {
            System.out.println("�̻��������������" + materialsFileUpload);
            Map<String, Object> result = UMFFileClient.post(apiContext, materialsFileUpload, file);
            System.out.println("�̻�������Ӧ�����" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] getBytes(File file){
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
}
